package com.then.component.club.ui;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModel;

import com.then.architecture.data.dto.Resource;
import com.then.component.club.entity.BaseLocation;
import com.then.component.club.entity.Club;
import com.then.component.club.repository.LocationRepository;
import com.then.component.club.repository.ClubRepository;
import com.then.component.club.request.ClubListReq;

import java.util.Collections;
import java.util.List;

import javax.inject.Inject;


/**
 * Created by 42524 on 2018/1/26.
 */

public class ClubListActivityViewModel extends ViewModel {

    private ClubRepository clubRepository;
    private LocationRepository locationRepository;

    @Inject
    public ClubListActivityViewModel(ClubRepository clubRepository, LocationRepository locationRepository) {
        this.clubRepository = clubRepository;
        this.locationRepository = locationRepository;
    }

    public LiveData<Resource<List<Club>>> getClubList(String userId) {
        LiveData<Resource<List<Club>>> liveData = clubRepository.getClubList(new ClubListReq(userId));
        liveData.observeForever(resource -> {
            if (liveData.getValue().data != null) {
                sortClubList(liveData.getValue().data);
                for (Club club : liveData.getValue().data) {
                    getLocationById(club.areaID).observeForever(resource1 ->
                    {
                        if (resource1.data != null) {
                            club.areaName.set(resource1.data.name_zh);
                        }
                    });
                }
            }
        });
        return liveData;
    }


    private void sortClubList(List<Club> clubs) {
        Collections.sort(clubs, (c1, c2) -> {
          return   c1.type-c2.type;
        });
    }

    private LiveData<Resource<BaseLocation>> getLocationById(String id) {
        if (id.length() == 3) {
            return locationRepository.queryCountryById(id);
        } else if (id.length() == 5) {
            return locationRepository.queryProvinceById(id);
        } else if (id.length() == 7) {
            return locationRepository.queryCityById(id);
        }
        return locationRepository.queryCountryById(id);
    }

}
